package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableLendAuditRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagLendAuditRecord {
    public long uid;
    public int last_loan_audit_status;
    public int last_loan_audit_time;
    public int last_loan_rejected_time;

    public static Logger LOG = LoggerFactory.getLogger(TagLendAuditRecord.class);

    public TagLendAuditRecord(
            long uid,
            int last_loan_audit_status,
            int last_loan_audit_time,
            int last_loan_rejected_time) {
        this.uid = uid;
        this.last_loan_audit_status = last_loan_audit_status;
        this.last_loan_audit_time = last_loan_audit_time;
        this.last_loan_rejected_time = last_loan_rejected_time;
    }

    public static TagLendAuditRecord init(long uid) {
        return new TagLendAuditRecord(uid, -1, -1, -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableLendAuditRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableLendAuditRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableLendAuditRecord.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableLendAuditRecord>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableLendAuditRecord> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagLendAuditRecord-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableLendAuditRecord>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableLendAuditRecord> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableLendAuditRecord>, String>() {
                                    ValueState<TagLendAuditRecord> lendAuditRecordVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        lendAuditRecordVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagLendAuditRecord>(
                                                                        "LendAuditRecordVState",
                                                                        TagLendAuditRecord.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableLendAuditRecord> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int last_loan_audit_status =
                                                value.f1.getLast_loan_audit_status();
                                        int updated_at = value.f1.getUpdated_at();

                                        TagLendAuditRecord tmpState = lendAuditRecordVState.value();
                                        TagLendAuditRecord curState =
                                                tmpState == null
                                                        ? TagLendAuditRecord.init(uid)
                                                        : tmpState;

                                        LOG.debug(
                                                "##TagLendAuditRecord dbg  uid: "
                                                        + uid
                                                        + " last_loan_audit_status: "
                                                        + last_loan_audit_status
                                                        + " updated_at: "
                                                        + updated_at
                                                        + " stateTime: "
                                                        + curState.getLast_loan_audit_time()
                                                        + " stateRtime: "
                                                        + curState.last_loan_rejected_time);

                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("uid", uid);
                                        if (curState.getLast_loan_audit_time() < updated_at) {
                                            //
                                            curState.last_loan_audit_time = updated_at;
                                            curState.last_loan_audit_status =
                                                    last_loan_audit_status;
                                            jsonObject.put(
                                                    "last_loan_audit_status",
                                                    (last_loan_audit_status == -1
                                                            ? null
                                                            : last_loan_audit_status));
                                            jsonObject.put(
                                                    "last_loan_audit_time",
                                                    (updated_at == -1 ? null : updated_at));
                                        }
                                        /** 0:拒绝 1:通过 不考虑借款状态发生改变的情况 */
                                        if (last_loan_audit_status == 0
                                                && (curState.last_loan_rejected_time
                                                        < updated_at)) {
                                            curState.last_loan_rejected_time = updated_at;
                                            jsonObject.put(
                                                    "last_loan_rejected_time",
                                                    (updated_at == -1 ? null : updated_at));
                                        }

                                        if (jsonObject.size() > 1) {
                                            out.collect(jsonObject.toString());
                                            lendAuditRecordVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getLast_loan_audit_status() {
        return last_loan_audit_status;
    }

    public int getLast_loan_audit_time() {
        return last_loan_audit_time;
    }

    public int getLast_loan_rejected_time() {
        return last_loan_rejected_time;
    }
}
